package com.example.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Iterator;

public class USB_Admin {

    private UsbManager usbManager;
    private UsbDevice usbDevice;
    private UsbInterface usbInterface;
    private UsbEndpoint usbEndpointIn;
    private UsbEndpoint usbEndpointOut;
    private UsbDeviceConnection usbDeviceConnection;

    private static int TIMEOUT = 5000;

    /*自己编写的USB管理类的构造函数*/
    public USB_Admin(Context context) {

        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        Log.v("USBManager：", "" + usbManager);
    }

    /*****************************USB相关的操作**********************************/

    /*获得USB的usbManager*/
    public UsbManager get_UsbManager() {

        return usbManager;
    }


    private HashMap<String, UsbDevice> deviceList;
    /*获得USB设备*/

    public UsbDevice get_UsbDevice(Intent intent) {   //这个USBDevice还有问题，暂时还得不到；

        /*使用意图过滤器的方法*/
        if (intent != null) {
            Log.d("intent: ", "" + intent.toString());
            if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {    //说明没有进入到这个if语句中
                usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);        //待查找；
                Log.v("USBDevice ", "" + usbDevice);
                if (usbDevice != null) {
                    Log.d("USB device attached: ", "" + usbDevice.getDeviceName());
                }
            }
        }

        deviceList = get_UsbManager().getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            usbDevice = deviceIterator.next();
            Log.e("ldm", "vid=" + usbDevice.getVendorId() + "---pid=" + usbDevice.getProductId());

            if (6353 == usbDevice.getVendorId() && 11 == usbDevice.getProductId()) {//找到指定设备
                break;
            }

        }

        /*使用枚举的方法做一下*/

        return usbDevice;
    }


    /*获得访问USB设备的权限*/
    /*若没有在清单文件中配置USB的意图过滤器，那么就需要手动通过这一步去获取权限*/
    /*
    public void getPermission(){
    }
    */

    /*获取USB设备的UsbInterface*/
    /*和系统提供的函数名有冲突*/
    public UsbInterface get_Interface(Context context) {

        usbInterface = usbDevice.getInterface(0);
        Log.v("USBInterface：", "" + usbInterface);
        if (usbInterface == null) {
            Toast.makeText(context, "can't get usbInterface", Toast.LENGTH_SHORT);
            return null;
        }

        return usbInterface;
    }

    /*
    作用：获取USB设备UsbEndpoint
    参数：
    0：表示获取输入端点
    1：表示获取输出端点
    */

    /*和系统提供的函数名有冲突*/
    public UsbEndpoint get_Endpoint(int i, Context context) {


        //获取输入端点
        if (i == 0) {

            if ((usbEndpointIn = usbInterface.getEndpoint(0)) != null) {

                Log.v("USBEndpointIn：", "" + usbEndpointIn);
                return usbEndpointIn;

            }
            Toast.makeText(context, "can't get usbEndpointIn", Toast.LENGTH_SHORT);


        } else if (i == 1) {     //获取输出端点

            if ((usbEndpointOut = usbInterface.getEndpoint(1)) != null) {

                Log.v("USBEndpointOut：", "" + usbEndpointOut);
                return usbEndpointOut;

            }
            Toast.makeText(context, "can't get usbEndpointOut", Toast.LENGTH_SHORT);

        }
        Toast.makeText(context, "can't get any usbEndpoint", Toast.LENGTH_SHORT);
        return null;

    }

    /*获得USB设备的UsbDeviceConnection*/
    public UsbDeviceConnection get_usbDeviceConnection(Context context) {

        if (usbManager.hasPermission(usbDevice)) {

            usbDeviceConnection = usbManager.openDevice(usbDevice);
            Log.v("USBDeviceConnection：", "" + usbDeviceConnection);


            return usbDeviceConnection;

        }
        Toast.makeText(context, "can't get usbDeviceConnection", Toast.LENGTH_SHORT);
        return null;

    }


    /*接收数据*/
    public int receive_Message(byte[] receiveBytes) {
        int ret = -1;
        if (usbEndpointIn != null) {
            ret = usbDeviceConnection.bulkTransfer(usbEndpointIn, receiveBytes, receiveBytes.length, TIMEOUT);
        } else {
            Log.v("receiveBytes: ", "failed");
        }

        return ret;
    }


    /*发送数据*/
    public int send_Message(byte[] sendBytes) {
        int ret = -1;
        if (usbEndpointOut != null) {
            ret = usbDeviceConnection.bulkTransfer(usbEndpointOut, sendBytes, sendBytes.length, TIMEOUT);
        } else {
            Log.v("Send: ", "failed");
        }

        return ret;

    }


    /*断开已连接的USB设备*/
    public void disconnect_USB(Context context) {
        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        usbDeviceConnection.releaseInterface(get_Interface(context));
                        usbDeviceConnection.close();
                    }
                }
            }
        };


    }

    /*获得设备的product-id和vendor-id*/
    public int get_ProductId() {
        return usbDevice.getProductId();

    }

    /*获得设备的vendor-id*/
    public int get_VendorId() {
        return usbDevice.getVendorId();

    }

}
